#include "spwm.h"
#include "main.h"
#include "gpio.h"
#include "tim.h"
#include "math.h"
#include "usart.h"
three_phrase_infor_t three_phrase_infor;
avergae_power_t avergae_power;

HAL_StatusTypeDef resset_device(void){
	
	HAL_GPIO_WritePin(SD1_GPIO_Port,SD1_Pin,0);
	HAL_GPIO_WritePin(SD2_GPIO_Port,SD2_Pin,0);
	HAL_GPIO_WritePin(SD3_GPIO_Port,SD3_Pin,0);
	
	HAL_TIM_Base_Start_IT(&htim1);
	HAL_TIM_Base_Start_IT(&htim2);
	HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_1);
	HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_2);
	HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_3);
	HAL_Delay(100);
	HAL_GPIO_WritePin(SD1_GPIO_Port,SD1_Pin,1);
	HAL_GPIO_WritePin(SD2_GPIO_Port,SD2_Pin,1);
	HAL_GPIO_WritePin(SD3_GPIO_Port,SD3_Pin,1);
	
	three_phrase_infor.HZ = 50;
	
	return HAL_OK;
}
unsigned char tail[4] = {0x00,0x00,0x80,0x7f};	

HAL_StatusTypeDef spwm_function(TIM_HandleTypeDef *htim_s,float u_max,TIM_HandleTypeDef *htim_c,avergae_power_t *avp){
	
	three_phrase_infor.Omega = 1/three_phrase_infor.HZ;
	if (u_max > MAX_COUNT) u_max = MAX_COUNT;
	three_phrase_infor.UA = three_phrase_infor.UB = three_phrase_infor.UC = u_max;
	__HAL_TIM_SET_COUNTER(htim_s,0);
	__HAL_TIM_SET_COUNTER(htim_c,0);
	while(1){
		
		uint32_t _TEMP_UA =  __HAL_TIM_GET_COUNTER(htim_c);
		uint32_t _TEMP_UB =  __HAL_TIM_GET_COUNTER(htim_c);
		uint32_t _TEMP_UC =  __HAL_TIM_GET_COUNTER(htim_c);
				
		_TEMP_UA =(uint32_t) MAX_COUNT*sinf(2*_PI* _TEMP_UA/65535+0) + MAX_COUNT;
		_TEMP_UB =(uint32_t) MAX_COUNT*sinf(2*_PI* _TEMP_UB/65535+_PI_3_2)+ MAX_COUNT;
		_TEMP_UC =(uint32_t) MAX_COUNT*sinf(2*_PI* _TEMP_UC/65535-_PI_3_2) + MAX_COUNT;
		
		avp->avergae_ua = _TEMP_UA;
		avp->avergae_ub = _TEMP_UB;
		avp->avergae_uc = _TEMP_UC;
		
		__HAL_TIM_SET_COMPARE(htim_s,TIM_CHANNEL_1,_TEMP_UA/2);
		__HAL_TIM_SET_COMPARE(htim_s,TIM_CHANNEL_2,_TEMP_UB/2);
		__HAL_TIM_SET_COMPARE(htim_s,TIM_CHANNEL_3,_TEMP_UC/2);

		HAL_UART_Transmit(&huart1,(uint8_t *)tail,sizeof(tail),0xfff);
		HAL_UART_Transmit(&huart1,(uint8_t *)avp,sizeof(avergae_power),0XFF);
	}	
	
	
}
